import BaseMapper from '../../db/mapper/BaseMapper'
import db from '../../db'
import TABLES from '../../db/util/table'
import { formatTimestamp, generateUUID } from '../../util'
import R from '../../vo/R'
import userStore from '../../store/user'
class SessionService {
  sessionListMapper = new BaseMapper(
    db,
    TABLES.SESSION_LIST.TABLE_NAME,
    TABLES.SESSION_LIST.TABLE_ID_COLUMN
  )

  chatListMapper = new BaseMapper(
    db,
    TABLES.SESSION_INFO.TABLE_NAME,
    TABLES.SESSION_INFO.TABLE_ID_COLUMN
  )

  /**
   * 初始化session
   * @returns {Promise<void>}
   */
  async initSession(data) {
    const sessionId =  data.sessionId
    const session = await  this.sessionListMapper.getOne({sessionId})

    // 如果不存在直接插入
    if (!session) {
      const res = await this.sessionListMapper.save(session)
      return R.ok(res.lastID)
    } else {
      data.id = session.id
      const res = this.sessionListMapper.updateById(data)
      return R.ok(res.lastID)
    }
  }

  /**
   * 创建会话
   * @param event 事件源
   * @param data 会话实体
   */
  async createSession(event, data) {
    const { contactId, createUser , lastTime } = data

    // 查询该会话是否已经创建
    const one = await this.sessionListMapper.getOne({ contactId, createUser: userStore.uid })

    console.log('会话：', one)
    if (one == null) {
      const session = {
        sessionId: generateUUID(),
        ...data
      }

      const res = await this.sessionListMapper.save(session)
      if (res.changes > 0) {
        return session.sessionId
      }
    } else {
      // 存在则更新时间
      const res = await this.sessionListMapper.updateById({
        isDel: 0,
        updateTime: Date.now(),
        sessionId: one.sessionId,
        isShow: 1,
        id: one.id
      })
      if (res.changes > 0) {
        return one.sessionId
      }
    }


  }

  async getSessionList(userId) {
    const result = await this.sessionListMapper.list({createUser: userId}, null, null, `update_time DESC`)
    if (result && result.list) {
      result.list = result.list.map((item) => {
        item.updateTime = formatTimestamp(+item.updateTime)
        return item
      })
    }
    return result
  }

  async getChatList(data) {
    return await this.chatListMapper.list(
      { sessionId: data.sessionId , createUser: userStore.uid },
      data.pageNumber,
      data.pageSize,
      `createTime DESC`
    )
  }
}

export default SessionService
